<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import { useRouter } from 'vue-router';
import unbindDialog from './components/unbindDialog.vue';
import { myCardList } from '@/common/api/bankCard';
import mitt from '@/utils/mitt';

const router = useRouter();

interface cardItem {
  bank_name: string;
  card_id: string;
  card_name: string;
  card_type: string;
  token_no: string;
}

// 定义引用
const unbindDialogRef = shallowRef<InstanceType<typeof unbindDialog>>();

const loading = ref(false);
const list = ref<cardItem[]>([]);

const onLoad = async () => {
  loading.value = true;
  try {
    const res = await myCardList({});
    list.value = res.result.list;
    mitt.emit('setHeader', res.result.data.hidekaifu !== 1);
  } catch {
    /** empty */
  } finally {
    loading.value = false;
  }
};
onLoad();

// 添加银行卡
const handleAddBankCard = () => {
  router.push('/bankCard/bindBankCard');
};

// 解绑银行卡
const handleUnbind = (token_no: string) => {
  unbindDialogRef.value?.open(token_no);
};
</script>
<template>
  <div class="bankCardList">
    <div
      v-for="item in list"
      :key="item.card_id"
      class="h-[90px] bg-[#C9132A] rounded-md flex items-center text-white relative mb-4"
    >
      <van-icon class="ml-7" name="credit-pay" color="#ffffff" size="30" />
      <div class="flex flex-col ml-3">
        <span class="text-base">{{ item.card_name }}</span>
        <span class="text-xs mt-2">{{ item.bank_name }}</span>
      </div>
      <div class="ml-auto mr-5 mt-5">{{ item.card_id }}</div>
      <div
        class="absolute top-0 right-0 text-xs bg-[rgba(255,255,255,0.25)] px-2 py-1 rounded-bl-md"
        @click="handleUnbind(item.token_no)"
      >
        解绑{{ item.card_type }}
      </div>
    </div>
    <div v-if="loading" class="flex justify-center pt-3">
      <van-loading>加载中...</van-loading>
    </div>
    <van-empty v-if="!list.length && !loading" />
    <div class="fixed bottom-0 left-0 w-full p-4">
      <van-button plain type="primary" block icon="add" color="#ED347F" size="large" @click="handleAddBankCard">
        添加银行卡
      </van-button>
      <!-- 底部安全区 -->
      <div class="van-safe-area-bottom"></div>
    </div>
    <unbindDialog ref="unbindDialogRef" @on-refresh="onLoad" />
  </div>
</template>
<style lang="less" scoped>
.bankCardList {
  height: 100%;
  padding: 10px;
}
</style>
